<?php

namespace app\controller\wmapi\order;

use app\controller\wmapi\approvalsetting\ApproveSettingController;
use app\controller\wmapi\examineapprove\AccountInformationApproveController;
use app\controller\wmapi\message\MessageNotifyController;
use app\controller\wmapi\PublicCommentController;
use App\Library\Y;
use app\model\WaAccountInformationExamineApproveFlow;
use app\model\WaAccountingInformation;
use app\model\WaAccountingInformationOperateLog;
use app\model\WaAccountingInformationRelevance;
use app\model\WaAdmins;
use app\model\WaApproveSetting;
use app\model\WaDepartment;
use app\model\WaMembers;
use app\model\WaOrders;
use app\model\WaOrdersOperateLog;
use app\model\WaOrdersPurchase;
use app\controller\wmapi\IndexController;
use app\model\WaOrdersPurchaseContract;
use app\model\WaOrdersRelevance;
use app\model\WaOrdersPurchaseRelevance;
use app\model\WaPayrollRequisitionExamineApprove;
use app\model\WaPayrollRequisitionExamineApproveFlow;
use app\model\WaProducts;
use app\model\WaPurchasedVehicles;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaPurchaseOrdersExamineApproveFlow;
use app\model\WaPurchasePayrollRequisition;
use app\model\WaSupplier;
use app\model\WaAccountInformationExamineApprove;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;

class AccountingInformationController extends Validate
{
    /**
     * 创建/编辑账单
     * @param Request $request
     * @return Response
     * 添加账单分配状态
     * 只要财务确认到帐前可编辑
     */
    public function accountingInformationCreate(Request $request)
    {
//
        // 出/入账类型 1定金  2 余款 3 定金退款 4 尾款退款 5客户违约金 6 赔付金
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        //操作日志记录入参
        $payment_voucher = json_encode($param['payment_voucher']);
//        $order_sn_ary = json_encode($param['order_sn_ary']);

//        if ($param['type'] == 1) {
//            $describe = $adminId->nickname . '确认' . $param['payer_name'] . '定金' . '资金到账';
//            $title = '定金到账确认';
//            $finance_no = 'DJ' . IndexController::getRandomNum(6);
//
//        } elseif ($param['type'] == 2) {
//            $describe = $adminId->nickname . '确认' . $param['payer_name'] . '尾款' . '资金到账';
//            $title = '尾款到账确认';
//            $finance_no = 'WK' . IndexController::getRandomNum(6);
//
//        } elseif ($param['type'] == 3) {
//            $describe = $adminId->nickname . '确认' . $param['payer_name'] . '退款';
//            $title = '用户退款确认';
//            $finance_no = 'TK' . IndexController::getRandomNum(6);
//
//        } elseif ($param['type'] == 4) {
//            $describe = $adminId->nickname . '确认' . $param['payer_name'] . '客户违约金';
//            $title = '客户违约金确认';
//            $finance_no = 'WY' . IndexController::getRandomNum(6);
//
//        } elseif ($param['type'] == 5) {
//            $describe = $adminId->nickname . '确认' . $param['payer_name'] . '赔付金';
//            $title = '赔付金确认';
//            $finance_no = 'PF' . IndexController::getRandomNum(6);
//
//        } else {
//            $describe = '暂无';
//            $title = '暂无';
//            $finance_no = 'No' . IndexController::getRandomNum(6);
//
//        }
        $finance_no = 'ZD' . IndexController::getRandomNum(6);
        $remark = $param['remark'];
        $payer_name = $param['payer_name']; // 付款人名称
        $receipt_number = $param['receipt_number'];// 回单编号 财务提供的到账或出账单中的一个唯一编码建议统一 避免重复确认到账
        try {
            \support\Db::beginTransaction();
            // 判断是更新还是创建
            $wai_condition = [];
            $wai_condition [] = ['receipt_number', '=', $receipt_number];
            $wai = WaAccountingInformation::find($wai_condition);
            if ($wai){
                $wai = json_decode($wai);

            }
            if ($param['customer_id']) {
                $customer_condition = [];
                $customer_condition [] = ['id', '=', $param['customer_id']];
                $customer_data = WaMembers::find($customer_condition);
                if ($customer_data) {
                    $customer_data = json_decode($customer_data);
                }
            }
            // 创建新的账单
            $confirm_data = [
                'receipt_number' => $param['receipt_number'],
                'finance_no' => $finance_no,
//                'order_sn_ary' => $order_sn_ary,// 数组
                'status' => 1,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payment_voucher' => $payment_voucher,
                'payment_amount' => $param['this_request_price'],
                'total_price' => $param['this_request_price'],
                'this_request_price' => $param['this_request_price'],
                'remark' => $param['remark'],
                'payer_name' => $param['payer_name'],
                'currency' => $param['currency'],
                'distributable_amount' => $param['this_request_price'], // 可分配金额
                'collecting_company' => $param['collecting_company'], // 收款公司
                'collecting_bank' => $param['collecting_bank'], // 收款银行
                'collecting_account' => $param['collecting_account'], // 收款账号
                'customer_id' => $param['customer_id'], // 客户id
                'customer_name' => $customer_data->name, // 客户名称
            ];

            // 根据收款账单信息判断是更新还是创建
            if (!$wai) {
                $confirm_data['created_at'] = dateTime();
                $accounting_information = WaAccountingInformation::created($confirm_data);
                if (!$accounting_information) {
                    $data_error = [
                        '错误：创建账单信息失败',
                        '账单信息' . $confirm_data,
                    ];
                    IndexController::logErrorNew('accountingInformationCreate', $data_error, $adminId, '');
                    \support\Db::rollBack();
                    return IndexController::errored('', '创建账单信息失败');
                }
            } else {
                if (in_array($wai->status, [1, 3])) {
                    //只有在财务确认到账之前  和 异常  可以编辑 其它状态不行
                    $confirm_data['updated_at'] = dateTime();
                    $accounting_information = WaAccountingInformation::updated($confirm_data, $wai_condition);
                    if (!$accounting_information) {
                        $data_error = [
                            '错误：更新账单信息失败',
                            '账单信息' . $confirm_data,
                        ];
                        IndexController::logErrorNew('accountingInformationCreate', $data_error, $adminId, '');
                        \support\Db::rollBack();
                        return IndexController::errored('', '更新账单信息失败');
                    }
                } else {
                    $data_error = [
                        '错误：只有财务确认到账前 和 异常下可以编辑',  //
                        '状态' . $wai->status,
                    ];
                    IndexController::logErrorNew('accountingInformationCreate', $data_error, $adminId, '');
                    \support\Db::rollBack();
                    return IndexController::errored('', '只有财务确认到账前 和 异常下可以编辑');
                }

            }
//
            // 账单日志
            $confirm_data_log = [
                'finance_no' => $finance_no,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => $payment_voucher,
                'transfer_amount' => $param['this_request_price'],
                'remark' => $remark,
                'currency' => $param['currency'],
            ];


            $confirm_data_log['created_at'] = dateTime();
            $accounting_information_log = WaAccountingInformationOperateLog::created($confirm_data_log);
            if (!$accounting_information_log) {
                $data_error = [
                    '错误：创建账单日志失败',
                    '账单日志信息' . $confirm_data_log,
                ];
                IndexController::logErrorNew('accountingInformationCreate', $data_error, $adminId, '');
                \support\Db::rollBack();
                return IndexController::errored('', '创建账单日志失败');
            }


//            $time = date('H:i:s', time());
//            $admin_ids = [];
//            // 钉钉消息通知
//            if ($admin_ids){
//                foreach ($admin_ids as $kadmin){
//                    $admin_condition = [];
//                    $admin_condition [] = ['id','=',$kadmin];
//                    $admin_data = WaAdmins::find($admin_condition);
//                    $admin_data = json_decode($admin_data);
//                    $data = [
//                        'mobile' => $admin_data->mobile,
//                        'title' => $title, // 标题
//                        'markdown' => '这笔订单'.$param['order_sn'].$time, // 内容
//                    ];
//                    $currentRoute  = $request->host();
//
//                    // 消息通知
//                    if ( $currentRoute == 'frontforeign.olivenev.com'){
//                        $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
//                    }
//                }
//
//            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logErrorNew('confirmationReceipt', $exception, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 账单列表
     * @param Request $request
     * @return Response
     */
    public function accountingInformationListBySales(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $whereIn = [];
//        $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
//        $whereIn = $next_epartment_members;
//        if($adminId->id == 39){
//            $whereIn = [];
//        }


        $condition = [];
        $between = [];


        if (array_key_exists('status', $param)) {
            if ($param['status']) {
                $condition [] = ['status', '=', $param['status']];
            }

        }

//        if ($param['start_time'] && $param['end_time']) {
//            $between [] = [$param['start_time'], $param['end_time']];
//        }

        // 只有财务部门不做限制 其它部门：
        // 限制条件 data_permission '数据权限 1 默认全部  2 只看自己 '
        // initiator_admin_id  审批发起人id
        // department_id  所属部门 42 43


        $fields = ['*'];
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $listOrder = WaAccountingInformation::listByAccInfo($page, $pageNum, $fields, $whereIn, $condition, $between);
        return IndexController::successed($listOrder, '销售订单账单列表');

    }

    /**
     * 账单详情
     * @param Request $request
     * @return Response
     */
    public function accountingInformationDetailBySales(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 主订单信息
//        $orderParentData = WaAccountingInformation::find(['finance_no' => $param['finance_no']]);
        $orderParentData = WaAccountingInformation::findApprove($adminId,['finance_no' => $param['finance_no']]);

        if (!$orderParentData) {
            return IndexController::errored('', '收款管理详情获取失败');
        }

        return IndexController::successed($orderParentData, '销售订单账单详情');

    }

    /**
     * 账单分配详情
     * @param Request $request
     * @return Response
     */
    public function accountingInformationDetailByAllocation(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 主订单信息
//        $orderParentData = WaAccountingInformation::find(['finance_no' => $param['finance_no']]);
        $orderParentData = WaAccountingInformation::findApproveByAllocation($adminId,$param['finance_relevance_no']);

        if (!$orderParentData) {
            return IndexController::errored('', '收款管理详情获取失败');
        }

        return IndexController::successed($orderParentData, '销售订单账单详情');

    }

    /**
     * 账单分配到订单 - 提交审批
     * @param Request $request
     * 只有财务确认到账后可分配
     * 已分配的订单可以重新分配
     *
     */
    public function allocationToOrder(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $finance_no = $param['finance_no']; //账单编号
        // 账单信息
        $condition_finance_no = [];
        $condition_finance_no [] = ['finance_no', '=', $finance_no];
        $finance_no_data = WaAccountingInformation::find($condition_finance_no);
        if ($finance_no_data) {
            $finance_no_data = json_decode($finance_no_data);
        } else {
            $data_error = [
                '错误：账单信息查询失败',
                '账单信息' . $finance_no . '///' . $finance_no_data,
            ];
            IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
            return IndexController::errored('','账单信息查询失败');
        }
        // 判断如果该笔账单下面有待审批的分配则不能重复提交
        $condition_relevance = [];
        $condition_relevance [] = ['finance_no', '=', $finance_no_data->finance_no];
        $condition_relevance [] = ['status', '=', 0]; // '(订单)状态 0 待审批 1正常(通过) 2审批失败 3 作废 4删除',
        $find_relevance = WaAccountingInformationRelevance::find($condition_relevance);
        if ($find_relevance) {
            $find_relevance = json_decode($find_relevance);

            if ($find_relevance) {
                $data_error = [
                    '错误：该笔账单还有未审批订单',
                    '账单编号' . $param['finance_no'] . '/待审批信息' . json_encode($find_relevance),
                ];
                IndexController::logErrorNew('allocationToOrder', $data_error);
                return IndexController::errored('','该笔账单还有未审批订单');
            }
        }
        // 总账单金额
        $finance_no_data->payment_amount;
        // 已分配金额
        $assigned_price = $finance_no_data->total_price;

        // 可分配金额
        $assignable_price = $finance_no_data->total_price;

        // 本次分配所以金额
        $order_all_transfer_amount = 0; // 新分配的几笔分配订单的总额度
        \support\Db::beginTransaction();
        try {
            //账单的分配编号
            $finance_relevance_no = 'FRN' . IndexController::getRandomNum(6);
            $order_transfer_data_ary = []; // (账单-订单)关联表需要添加的 分配数据
            $order_transfer_data_log = []; // 账单需要添加的日志
            $order_allocation_data = $param['order_allocation_data'];

            if ($order_allocation_data) {
                // 这一步和下一步一模一样  但是这一步步没有创建 避免金额超出还会有记录限制分配
                foreach ($order_allocation_data as $ko) {
                    $order_all_transfer_amount = $order_all_transfer_amount + round($ko['transfer_amount'], 2);

                    // 判断金额类型是否与订单的金额类型一致不一致不能通过
                    $sales_fund_type_condition = [];
                    $sales_fund_type_where_in = [];
                    $sales_fund_type_condition [] = ['finance_no', '=', $finance_no_data->finance_no];
                    $sales_fund_type_condition [] = ['type', '=', $ko['type']];
                    $sales_fund_type_condition [] = ['status', '<', 2];
                    // 已分配的金额 = 待审批的  和 已分配的总额
                    $sums_by_sales_fund_type = WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_type_condition, $sales_fund_type_where_in);
                    //此次要分配的金额
                    $ko['transfer_amount'];
                    // 销售订单信息
                    $sales_order_condition = [];
                    $sales_order_condition [] = ['order_sn', '=', $ko['order_sn_parent']];
                    $sales_data = WaOrders::find($sales_order_condition);

                    // 判断销售订单需要分配的金额是否超出
                    if (in_array($ko['type'], [1, 2])) {

                        if ($sales_data) {
                            $sales_data = json_decode($sales_data);
                        }
                        if ($ko['type'] == 1) {
                            $sales_amount = $sales_data->deeposit_amount;// 定金
                            $type_name = '定金';
                        }
                        if ($ko['type'] == 2) {
                            $sales_amount = round($sales_data->total_amount, 2) - round($sales_data->deeposit_amount, 2); // 尾款
                            $type_name = '尾款';
                        }
                        //账单可以分配的金额
                        $finance_no_data->payment_amount;
                        // 订单需要分配的金额
                        $need_balance = round($sales_amount, 2) - round($sums_by_sales_fund_type, 2); //需要根据类型区分
                        $sums_by_sales_fund_type; // 根据账单 编号/类型 查询 账单已经分配的额度（区分 定金/尾款）

                        // 此次分配的金额
                        $ko['transfer_amount'];
                        // 总分配金额不能超出账单收入金额, 也不能超出订单中设定的金额

                        // 分配金额不能超出账单金额
                        if ($finance_no_data->payment_amount < $ko['transfer_amount']){
                            $data_error = [
                                '错误：账单可以分配的金额 小于 订单需要分配的金额 (额度超了)',
                                '账单可以分配的金额' . $finance_no_data->payment_amount. '订单需要分配的金额' . $ko['transfer_amount'],
                            ];
                            IndexController::logErrorNew('allocationToOrder', $data_error);
                            \support\Db::rollBack();
                            return IndexController::errored('','账单可以分配的金额 小于 订单需要分配的金额 (额度超了)');
                        }
                        // 实际分配金额 不能超出 订单中类型对应的金额
                        if ($need_balance < $ko['transfer_amount']){
                            $data_error = [
                                '错误：订单需要分配的金额 小于 此次分配的金额 (不需要分配这么多)',
                                '账单可以分配的金额' . $need_balance . '订单需要分配的金额' . $ko['transfer_amount'],
                            ];
                            IndexController::logErrorNew('allocationToOrder', $data_error);
                            \support\Db::rollBack();
                            return IndexController::errored('','订单需要分配的金额 小于 此次分配的金额 (不需要分配这么多)');
                        }




                    }
                    // 必须是要同一个客户才能分配(就是订单的客户id 必须与账单的客户id 一致)
                    if ($sales_data->user_id != $finance_no_data->customer_id) {
                        $data_error = [
                            '错误：客户信息不一致',
                            '销售订单客户' . $sales_data->user_name . '账单客户' . $finance_no_data->customer_id,
                        ];
                        IndexController::logErrorNew('allocationToOrder', $data_error);
                        \support\Db::rollBack();
                        return IndexController::errored('','客户信息不一致');

                    }


                    // 已经分配的不能重新分配，那么分配表的数据是不能删除只能更新状态
                    // 账单关联表添加对应订单的分配金额 未填写

                    $order_transfer_data = [
                        'finance_no' => $param['finance_no'],
                        'finance_relevance_no' => $finance_relevance_no,
                        'order_sn_parent' => $ko['order_sn_parent'],
                        'currency' => $finance_no_data->currency,
                        'type' => $ko['type'],
                        'admin_id' => $adminId->id,
                        'admin_name' => $adminId->nickname,
                        'transfer_amount' => $ko['transfer_amount'],
                        'status' => 0, // 账单状态 0 待审批 1正常(通过) 2审批失败 3 作废 4删除,
                        'created_at' => dateTime(),
                    ];
                    if (array_key_exists('to_be_allocated',$ko)){
                        if ($ko['to_be_allocated']){
                            $order_transfer_data['to_be_allocated'] = $ko['to_be_allocated'];
                        }
                    }


                    if ($order_transfer_data) {
                        array_push($order_transfer_data_ary, $order_transfer_data);
                    }
                }



                // 根据账单编号查询 账单已经分配的额度（包括 定金/尾款）
                $sales_fund_finance_no_condition = [];
                $sales_fund_finance_no_where_in = [];
                $sales_fund_finance_no_condition [] = ['finance_no', '=', $finance_no_data->finance_no];
                $sales_fund_finance_no_condition [] = ['status', '<', 2];
                // 已分配的金额 = 待审批的  和 已分配的总额
                $sums_by_sales_fund_finance_no = WaAccountingInformationRelevance::sumsBySalesFundByFinanceNo($sales_fund_finance_no_condition, $sales_fund_finance_no_where_in);


                // 账单金额 不能小于已分配金额(包括待审批的)
                if (round($finance_no_data->payment_amount,2) <  round($sums_by_sales_fund_finance_no,2)){
                    $data_error = [
                        '错误：账单可以分配的金额 小于 账单已分配金额',
                        '账单可以分配的金额' . $finance_no_data->payment_amount . '账单已分配金额' . $sums_by_sales_fund_finance_no,
                    ];
                    IndexController::logErrorNew('allocationToOrder', $data_error);
                    \support\Db::rollBack();
                    return IndexController::errored('','账单可以分配的金额 小于 账单已分配金额');
                }else{
                    // 已分配金额总和（包括新分配的(总和)）
                    $sums_by_sales_fund_new = round($sums_by_sales_fund_finance_no,2) + $order_all_transfer_amount;
                    // 账单总金额 不能小于最后的已分配金额总和（包括新分配的）
                    if (round($finance_no_data->payment_amount,2) <  round($sums_by_sales_fund_new,2)){
                        $data_error = [
                            '错误：账单可以分配的金额 小于 新旧总共的分配金额',
                            '账单可以分配的金额' . $finance_no_data->payment_amount . '新旧总共的分配金额' . $sums_by_sales_fund_new,
                        ];
                        IndexController::logErrorNew('allocationToOrder', $data_error);
                        \support\Db::rollBack();
                        return IndexController::errored('','超出可分配的金额');
                    }
                }









                // 新分配的几笔分配订单的总额度  账单可分配额度
                if ($order_all_transfer_amount > round($finance_no_data->payment_amount, 2)) {
                    $data_error = [
                        '错误：分配金额超出可分配金额',
                        '几笔分配订单的总额度' . $order_all_transfer_amount,
                        '账单可分配额度' . $finance_no_data->payment_amount,

                    ];
                    IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
                    \support\Db::rollBack();
                    return IndexController::errored('','分配金额超出可分配金额');
                }

                if ($order_transfer_data_ary){
                    foreach ($order_transfer_data_ary as $order_transfer_data) {
                        $cre_rel = WaAccountingInformationRelevance::created($order_transfer_data);
                        if (!$cre_rel) {
                            $data_error = [
                                '错误：添加分配订单金额信息失败',
                                '销售订单编号' . $ko['order_sn_parent'] . '信息' . json_encode($order_transfer_data),
                            ];
                            IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
                            \support\Db::rollBack();
                            return IndexController::errored('','添加分配订单金额信息失败');
                        }
                    }
                }

            }



            //更新账单信息
//            * 总金额-原
//            * 已分配金额
//            * 可分配金额-原
//            * 待审批金额-原
//            * 当前分配到订单的总额度
//            * 可分配金额-新 = 可分配金额-原 - 当前分配到订单的总额度    或   总金额-原 - 待审批金额-原 - 已分配金额 - 当前分配到订单的总额度
//            * 待审批金额-新 = 待审批金额 + 当前分配到订单的总额度 (不能超过总金额)
//            $finance_no_data->distributable_amount; // 可分配金额-原
//            $finance_no_data->pending_approval_amount;// 待审批金额-原
//            $order_all_transfer_amount; // 当前分配到订单的总额度
//            $distributable_amount = round($finance_no_data->distributable_amount, 2) - round($order_all_transfer_amount, 2); // 可分配金额-新
//            if ($distributable_amount < 0) {
//                $data_error = [
//                    '错误：超出可分配金额',
//                    '当前分配到订单的总额度' . $order_all_transfer_amount,
//                    '可分配金额-原' . $finance_no_data->distributable_amount,
//                    '可分配金额-新' . $distributable_amount,
//                ];
//                IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
//                \support\Db::rollBack();
//                return IndexController::errored('','超出可分配金额');
//            }
//
//            $pending_approval_amount = round($finance_no_data->pending_approval_amount, 2) + round($order_all_transfer_amount, 2); // 待审批金额-新 = 待审批金额 + 当前分配到订单的总额度
//            $allocated_amount = $finance_no_data->allocated_amount; // 已分配金额
//            $allocated_amount = 0;// 已分配金额
//            $distributable_amount = 0;//可分配金额-新
//            $pending_approval_amount = 0;// // 待审批金额-新 = 待审批金额 + 当前分配到订单的总额度
//            if (round($finance_no_data->distributable_amount, 2) < round($pending_approval_amount, 2)) {
//                $data_error = [
//                    '错误：待审核金额超出可分配金额',
//                    '已分配金额' . $allocated_amount,
//                    '当前分配到订单的总额度' . $order_all_transfer_amount,
//                    '可分配金额-原' . $finance_no_data->distributable_amount,
//                    '可分配金额-新' . $distributable_amount,
//                    '待审批金额-原' . $finance_no_data->pending_approval_amount,
//                    '待审批金额-新' . $pending_approval_amount,
//                ];
//                IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
//                \support\Db::rollBack();
//                return IndexController::errored('','待审核金额超出可分配金额');
//            }
//
//            $conditon_accounting_information = [];
//            $conditon_accounting_information [] = ['finance_no', '=', $param['finance_no']];; //账单编号
//            $accounting_information_data = [
////                'wai_approve_transfer_data_ary' => json_encode($order_transfer_data_ary), // 待审批后分配的(账单-订单)金额数据
////                'wai_approve_log_data' => json_encode($order_allocation_data), // 待审批后创建的日志
//                'distributable_amount' => $distributable_amount, // 可分配金额
//                'pending_approval_amount' => $pending_approval_amount, // 待审批金额
//                'admin_id' => $adminId->id,
//                'admin_name' => $adminId->nickname,
//                'updated_at' => dateTime(),
//            ];
//
//
//            $up_accounting_information = WaAccountingInformation::updated($accounting_information_data, $conditon_accounting_information);
//            if (!$up_accounting_information) {
//                $data_error = [
//                    '错误：更新账单信息失败',
//                    '账单信息' . json_encode($accounting_information_data),
//                    '账单更新条件' . json_encode($conditon_accounting_information),
//                ];
//                IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
//                \support\Db::rollBack();
//                return IndexController::errored('','更新账单信息失败');
//            }





            // 添加账单提交审批日志
            $accounting_information_data_log = [
                'finance_no' => $param['finance_no'],
                'finance_relevance_no' => $finance_relevance_no,
                'wai_approve_transfer_data_ary' => json_encode($order_transfer_data_ary), // 待审批后分配的(账单-订单)金额数据
                'wai_approve_log_data' => json_encode($order_allocation_data), // 待审批后创建的日志
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'type' => $finance_no_data->type,
                'currency' => $finance_no_data->currency,
                'status' => 1, // '(订单)状态 0 待审批 1正常(通过) 2审批失败 3 作废 4删除',,

                'created_at' => dateTime(),
                'describe' => $adminId->nickname . '提交了一次分配金额审批',
            ];
            $add_accounting_information_log = WaAccountingInformationOperateLog::created($accounting_information_data_log);
            if (!$add_accounting_information_log) {
                $data_error = [
                    '错误：账单日志添加失败',
                    '账单操作日志信息' . $accounting_information_data_log,
                ];
                IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
                \support\Db::rollBack();
                return IndexController::errored('','账单日志添加失败');
            }


            $send_before = [];
            $send_after = [];

            if (array_key_exists('send_before',$param)){
                if ($param['send_before']){
                    $send_before = $param['send_before'];
                }
            }

            if (array_key_exists('send_after',$param)){
                if ($param['send_after']){
                    $send_after = $param['send_after'];
                }
            }

            // 获取当前用户对应部门所设置的审批流设置
//        $flow = ApproveSettingController::flowStting(2, $department_id);
            if (array_key_exists('flow',$param)){
                $flow = $param['flow'];
                $admin_ids = json_encode($flow[0]['approve_admin_id']);

//            可以把抄送人加到消息通知组里一起发送，但是有个问题抄送人不一定有权限看  所以 需要要个单独的 抄送消息 具体要通知什么消息

            }else{
                if (array_key_exists('sort', $param)){
                    if ($param['sort']){
                        $sort = $param['sort'];
                    }else{
                        $sort = 0;
                    }
                }else{
                    $sort = 0;
                }
                $flow = ApproveSettingController::flowSttingBySort(8,$sort);// sort默认选第一个
                $send_after = ApproveSettingController::flowSttingBySendBefore(8,$sort);// 抄送人 - 前 默认选第一个
                $send_before = ApproveSettingController::flowSttingBySendAfter(8,$sort);// 抄送人 - 前 默认选第一个
                $admin_ids = json_encode($flow[0]->approve_admin_id);
            }



            $ai_no = 'AIACCINFONO' . IndexController::getRandomNum(6);
            $data_ai_no = [
                'finance_no' => $param['finance_no'],
                'finance_relevance_no' => $finance_relevance_no,
                'ai_no' => $ai_no, // 账单金额分配审批编号
                'total_amount' => round($finance_no_data->total_price, 2), // 总金额
                'customer_id' => $finance_no_data->customer_id, // 用户编号id
                'customer_name' => $finance_no_data->customer_name, // 用户名字
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'initiator_admin_id' => $adminId->id, //
                'currency' => $finance_no_data->currency, // '币种 1 人民币 2 美元 3 欧元
                'type' => $ko['type'], // 出/入账类型 1定金  2 余款 3 定金退款 4 尾款退款 5 客户违约金 6 赔付金
//                'price_name' => $adminId->id, // 款项类目名称
                'status' => 0, //'状态 0 审核中 1 通过 2 驳回 3撤回',
                'created_at' => dateTime(), // 创建时间
                'transfer_data_ary' => dateTime(), // 分配的(账单-订单)金额数据
                'approve_flow' => json_encode($flow), // 当前账单金额分配的审批流流程
            ];
            if ($send_before) {
                $data_ai_no['approve_flow_send_before'] = json_encode($send_before);
            }
            if ($send_after) {
                $data_ai_no['approve_flow_send_after'] = json_encode($send_after);
            }

            $add_ai_no = WaAccountInformationExamineApprove::create($data_ai_no); // 创建的审批id
            if (!$add_ai_no) {
                $data_error = [
                    '错误：创建账单审批失败',
                    '审批id' . $add_ai_no,
                ];
                IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
                \support\Db::rollBack();
                return IndexController::errored('','创建账单审批失败');
            }


            $approve_log_data = [
                'finance_no' => $param['finance_no'],
                'finance_relevance_no' => $finance_relevance_no,
                'ai_no' => $ai_no, // 账单金额分配审批编号
                'check_id' => $add_ai_no, // 审核id
//                'check_on' => $sales_approve->sale_no, // 审核编号
                'admin_ids' => $admin_ids, //  （撤回的时候可以是空数组）
                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'status' => 0, // 审核状态 0 待审核 1审批通过 2 审批驳回  3作废 4  删除
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'describe' => '待' . $admin_ids . '审核',

            ];
            $res = WaAccountInformationExamineApproveFlow::create($approve_log_data);
            if (!$res) {
                $data_error = [
                    '错误：创建账单审批日志失败',
                    '审批流id' . $res,
                ];
                IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
                \support\Db::rollBack();
                return IndexController::errored('','创建账单审批日志失败');
            }

            // 更新账单分配表信息
            $accf_relevance_condition = [];
            $accf_relevance_condition [] = ['finance_relevance_no','=',$finance_relevance_no];
            $accf_relevance_data = [
                'ai_no' => $ai_no, // 账单金额分配审批编号
                'wai_approve_transfer_data_ary' => json_encode($order_transfer_data_ary), // 待审批后分配的(账单-订单)金额数据
                'wai_approve_log_data' => json_encode($order_allocation_data), // 待审批后创建的日志
                'updated_at' => dateTime(),
            ];
            $accf_relevance_res = WaAccountingInformationRelevance::updated($accf_relevance_data,$accf_relevance_condition);
            if (!$accf_relevance_res) {
                $data_error = [
                    '错误：同步账单分配表信息信息失败',
                ];
                IndexController::logErrorNew('allocationToOrder', $data_error, $adminId, '');
                \support\Db::rollBack();
                return IndexController::errored('','同步账单分配表信息信息失败');
            }

            IndexController::logSuccessed('allocationToOrderApprove-massage', '账单发起审批消息通知', $adminId);

            // 钉钉消息通知
            $time = dateTime();
            $admin_ids = json_decode($admin_ids);
            if ($admin_ids){
                foreach ($admin_ids as $kadmin){
                    $admin_condition = [];
                    $admin_condition [] = ['id','=',$kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '账单审批', // 标题
                        'markdown' => '有一条账单'. $param['finance_no'] . '需要(轮到)你帮忙审批/'.$time, // 内容
                    ];
                    IndexController::logSuccessed('allocationToOrderApprove-massage','222222222223333333333',$adminId);
                    IndexController::logSuccessed('allocationToOrderApprove-massage',$data,$adminId);
                    $currentRoute  = $request->host();
                    IndexController::logSuccessed('allocationToOrderApprove-massage','3333333333444444444444444',$adminId);

                    IndexController::logSuccessed('allocationToOrderApprove-massage','路由'.$currentRoute,$adminId);
                    IndexController::logSuccessedtest('allocationToOrderApprove-massage','路由'.$currentRoute,$adminId);

                    // 消息通知
                    if ( $currentRoute == 'frontforeign.olivenev.com'){
                        IndexController::logSuccessed('allocationToOrderApprove-massage','444444444444444555555555',$adminId);
                        IndexController::logSuccessed('allocationToOrderApprove-massage',$data,$adminId);
                        $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }


            // 钉钉消息通知 - 账单发起审批通知(抄送)
            if ($send_before){
                    $admin_ids = $send_before;
                    foreach ($admin_ids as $kadmin){
                        $admin_condition = [];
                        $admin_condition [] = ['id','=',$kadmin];
                        $admin_data = WaAdmins::find($admin_condition);
                        $admin_data = json_decode($admin_data);
                        $data = [
                            'mobile' => $admin_data->mobile,
                            'title' => '账单发起审批通知', // 标题
                            'markdown' => '有一条由'.$adminId->nickname.'发起的账单审批订单'. $param['finance_no'] . '/'.$time, // 内容
                        ];
                        IndexController::logSuccessed('allocationToOrderApprove-massage','222222222223333333333',$adminId);
                        IndexController::logSuccessed('allocationToOrderApprove-massage',$data,$adminId);
                        $currentRoute  = $request->host();
                        IndexController::logSuccessed('allocationToOrderApprove-massage','3333333333444444444444444',$adminId);

                        IndexController::logSuccessed('allocationToOrderApprove-massage','路由'.$currentRoute,$adminId);
                        IndexController::logSuccessedtest('allocationToOrderApprove-massage','路由'.$currentRoute,$adminId);

                        // 消息通知
                        if ( $currentRoute == 'frontforeign.olivenev.com'){
                            IndexController::logSuccessed('allocationToOrderApprove-massage','444444444444444555555555',$adminId);
                            IndexController::logSuccessed('allocationToOrderApprove-massage',$data,$adminId);
                            $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                        }
                    }

            }


            \support\Db::commit();
            return IndexController::successed('', '分配成功已提交审批');
        } catch (\Throwable  $exception) {
            // 关键点3：异常时强制回滚
//            if (\support\Db::transaction() > 0) {
//                \support\Db::rollBack();
//            }
            IndexController::logErrorNew('allocationToOrder', $exception->getMessage());
            IndexController::logErrorNew('allocationToOrder', $exception->getTraceAsString());
            \support\Db::rollBack();
            return IndexController::errored($exception, '分配失败');
        }

    }

    /**
     * 收款管理详情
     * @param Request $request
     * @return Response
     */
    public function accountingInformationDetail(Request $request)
    {
        $param = $request->all();
        // 主订单信息
        $orderParentData = WaAccountingInformation::find(['finance_no' => $param['finance_no']]);
        if (!$orderParentData) {
            return IndexController::errored('', '收款管理详情获取失败');
        }

        return IndexController::successed($orderParentData, '收款管理详情');

    }

    /**
     * 销售订单-到账异常
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function financeException(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $wai = WaAccountingInformation::find(['finance_no' => $param['finance_no']]);
        $wai = json_decode($wai);
        if (!$wai) {
            return IndexController::errored('', '到账信息获取失败');
        }

        \support\Db::beginTransaction();
        try {
            // 创建 财务确认定金到账
            $confirm_data = [
                'status' => 3,
                'type' => $wai->type,// 类型 1 定金 2 余款
                'exception_reason' => $param['exception_reason'],// 异常原因
                'exception_admin_id' => $adminId->id,//
                'exception_admin_name' => $adminId->nickname,//
                'updated_at' => dateTime(),
            ];
            $confirm_where = [];
            $confirm_where [] = ['finance_no', '=', $param['finance_no']];
            $accounting_information = WaAccountingInformation::updated($confirm_data, $confirm_where);
            if (!$accounting_information) {
                $data_error = [
                    '错误：更新 待财务确认到账 失败',
                    'finance_no：'.$param['finance_no'],
                ];
                IndexController::logErrorNew('financeException', $data_error);
                \support\Db::rollBack();
                return IndexController::errored('', '更新 待财务确认到账 失败');
            }



            // 添加账单操作日志
            $accounting_information_data_log = [
                'finance_no' => $param['finance_no'],
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
                'describe' => $param['exception_reason'],
            ];
            $add_accounting_information_log = WaAccountingInformationOperateLog::created($accounting_information_data_log);
            if (!$add_accounting_information_log) {
                $data_error = [
                    '错误：账单操作日志添加失败',
                    '账单操作日志信息' . $accounting_information_data_log,
                ];
                IndexController::logErrorNew('fundsConfirmationByFinance', $data_error, $adminId, '');
                \support\Db::rollBack();
            }


            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logErrorNew('financeException', $param);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

//
    /**
     * 账单作废
     *需要注意的点：
     * 正常账单可分配是必须通过财务同意的所以账单作废的可能性不大
     * 财务确认之前是可以作废的  但是实际上只要是可编辑的 应该是不需要作废的操作 但也不排除就要作废的可能
     * 除非客户要退款 但是退款不走作废流程
     * 如果有已分配的订单正常是不能作废：
     *  账单作废关系到已分配的订单，也关系到已审批的订单  和 销售订单 定金尾款 和是否足额执行下一个状态的问题
     *  如果作废 会影响销售订单状态 首先得先考虑这笔账单已分配的记录种分配的 类型 如 定金  尾款
     *  如果有定金 则得同时判断销售订单的状态是否已经执行到采购
     *  如果有尾款 则需要考虑 采购对订单的操作 和 跟单的流程
     * 但实际业务中可能存在需要作废的可能：
     *
     *
     */
    public function accountingInformationCancel(Request $request)
    {

    }

    /**
     * 账单撤回分配审批
     * 正常待审批只会有一笔
     */
    public function accountInforApproveWithdraw(Request $request)
    {
        //账单状态
        PublicCommentController::账单状态;
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $find_rel = WaAccountingInformationRelevance::find([
            ['finance_no', '=', $param['finance_no']],
            ['status','=',0]
        ]); // 正常待审批只会有一笔
        $find_rel = json_decode($find_rel);
        if (!$find_rel) {
            $data_error = [
                '错误：没有账单分配待审批订单',
                'finance_no：'.$param['finance_no'],
            ];
            IndexController::logErrorNew('accountInforApproveWithdraw', $data_error);
            \support\Db::rollBack();
            return IndexController::errored('', '没有账单分配待审批订单');
        }

        \support\Db::beginTransaction();
        try {

            // 当前这笔分配的账单对应的审批记录作废掉
            // 作废当前这笔待分配审批的账单分配记录
            //记录操作日志

            // 账单审批状态修改
            $accounting_information = AccountInformationApproveController::AccountInformationApproveStatusUpdate($adminId,$find_rel->ai_no);
            if (!$accounting_information) {
                $data_error = [
                    '错误：账单审批状态修改失败',
                    '审批编号：'.$find_rel->ai_no,
                ];
                IndexController::logErrorNew('accountInforApproveWithdraw', $data_error);
                \support\Db::rollBack();
                return IndexController::errored('', '账单审批状态修改失败');
            }
            $ac_info_up_data = [
                'status' => 4, // 作废
                'ai_no' => $find_rel->ai_no,
                'admin_id' => $adminId->id,// 异常原因
                'admin_name' => $adminId->nickname,// 异常原因
                'updated_at' => dateTime(),
            ];
            $ac_info_up_condition = [];
            $ac_info_up_condition [] = ['ai_no','=',$find_rel->ai_no];
            $order_up = WaAccountingInformationRelevance::updated($ac_info_up_data, $ac_info_up_condition);
            if (!$order_up) {
                return IndexController::errored('', '更新订单失败');
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logErrorNew('financeException', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 账单退款
     * 客户退款需要注意的点：
     * 退款只能退可分配金额的钱 已分配的钱不能退 需要把已分配的订单撤回来(但是已分配的订单是不能作废的,但是已分配的订单可以重新分配，需要再次审批)
     * 退款的多样性：
     *  有可能只退部分尾款(可能某辆车客户不要了 但是钱已经打过来  其它车还是要的 客户的选择 下次购车分配 或 硬性退款(概率比较小))
     *  有可能定金尾款全退（取消订单）,需要把分配的金额全部都退回账单 需要操作的事务：
     *      修改顶顶那状态，账单金额收回后删除和这个取消订单的分配信息 到那时要添加金额撤回记录
     *  有可能只退定金 这种情况一般是取消订单如果只是退订单中的极个别车那么多余的款项会被分配到车辆的尾款  一般这种就是销售订单也会作废
     */
    public function accountingInformationRefund(Request $request)
    {

    }

    /**
     * 违约金
     */

    /**
     * 赔偿金
     */

    /**
     * 重新分配
     */

    /**
     * 销售订单-财务确认资金到账
     *订单状态:
     *  先不能变成订单待采购  需要等分配完统计金额后确认金额满足 定金 或余额的 额度时 才会自动同步状态
     * @param Request $request
     * @return Response
     */
    public function fundsConfirmationByFinance(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $wai = WaAccountingInformation::find(['finance_no' => $param['finance_no']]);
        $wai = json_decode($wai);
        if (!$wai) {
            return IndexController::errored('', '资金到账信息获取失败');
        }


        if (array_key_exists('voucher', $param)) { // 财务确认凭证
            $voucher = $param['voucher'];
        } else {
            $voucher = [];
        }

        if (array_key_exists('payer_name', $param)) { //
            $payer_name = $param['payer_name'];
        } else {
            $payer_name = $wai->payer_name;
        }


        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            $describe = $adminId->nickname . '财务确认资金到账';

            // 创建 财务确认定金到账
            $confirm_data = [
                'status' => 2,// 财务确认资金到账（待分配）
                'finance_confirm_entry_admin_id' => $adminId->id,
                'finance_confirm_entry_admin_name' => $adminId->nickname,
                'voucher' => json_encode($voucher), // 财务确认凭证
                'payment_amount' => $wai->this_request_price,
                'this_request_price' => $wai->this_request_price,
                'payer_name' => $payer_name,
                'updated_at' => dateTime(),
            ];

            $confirm_where = [];
            $confirm_where [] = ['finance_no', '=', $param['finance_no']];
            $accounting_information = WaAccountingInformation::updated($confirm_data, $confirm_where);
            if (!$accounting_information) {
                \support\Db::rollBack();
                return IndexController::errored($accounting_information, '财务确认资金到账失败');

            }


            // 添加账单操作日志
            $accounting_information_data_log = [
                'finance_no' => $param['finance_no'],
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
                'describe' => $describe,
            ];
            $add_accounting_information_log = WaAccountingInformationOperateLog::created($accounting_information_data_log);
            if (!$add_accounting_information_log) {
                $data_error = [
                    '错误：账单操作日志添加失败',
                    '账单操作日志信息' . $accounting_information_data_log,
                ];
                IndexController::logErrorNew('fundsConfirmationByFinance', $data_error, $adminId, '');
                \support\Db::rollBack();
            }


            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logErrorNew('financeConfirmation', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }








    /**
     * 作废收款管理
     * @param Request $request
     * @return Response
     */
    public function accountingInformationList(Request $request)
    {
        return IndexController::errored('', '20250610作废-跟换新接口 /admin-order-accounting-information-list-by-sales');
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $condition = [];
        $between = [];
        if (array_key_exists('type', $param)) {
            if ($param['type']) {
                $condition [] = ['type', '=', $param['type']];
            }

        }

        if (array_key_exists('status', $param)) {
            if ($param['status']) {
                $condition [] = ['status', '=', $param['status']];
            }

        }

//        if ($param['start_time'] && $param['end_time']) {
//            $between [] = [$param['start_time'], $param['end_time']];
//        }
        $fields = ['*'];
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $listOrder = WaAccountingInformation::list($page, $pageNum, $fields, $condition, $between);
        return IndexController::successed($listOrder, '收款管理');

    }

    /**
     * 作废-更新-定金确认到账 (4 待支付定金 变成 5订单采购中 )
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function confirmationDepositReceipt(Request $request)
    {
        return IndexController::errored('', '20250610作废-独立出来账单业务');
        //销售订单状态
        PublicCommentController::销售订单状态;
        // 订单状态 4 待支付定金
        // 订单状态 1 待核验(通过2 审批中(创建审批) / 不通过0 撤回草稿)
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        //操作日志记录入参
        $payment_voucher = json_encode($param['payment_voucher']);
        $describe = $adminId->nickname . '确认订单' . $param['order_sn'] . '定金到账修改订单状态为待财务确认到账';
        $remark = $param['remark'];
        $confirm_time = dateTime(); // 确认时间
        $payer_name = $param['payer_name']; // 付款人名称
        $status = 12; // 财务确认到账

        $orders = WaOrders::find(['order_sn' => $param['order_sn']]);
        $orders = json_decode($orders);
        if (!$orders) {
            return IndexController::errored('', '获取订单信息失败');
        }
        \support\Db::beginTransaction();
        try {

            // 判断是更新还是创建
            $wai_condition = [];
            $wai_condition [] = ['order_sn_parent', '=', $param['order_sn']];
            $wai_condition [] = ['type', '=', 1]; // 定金
            $wai = WaAccountingInformation::find($wai_condition);
            $wai = json_decode($wai);


            //操作日志记录入参
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payment_voucher' => $payment_voucher,
                'payment_amount' => $param['this_request_price'],
                'this_request_price' => $param['this_request_price'],
                'payer_name' => $payer_name,
                'type' => 1,// 类型 1 定金 2 余款
                'confirm_time' => dateTime(),
            ];

            // 根据收款账单信息判断是更新还是创建
            if (!$wai) {
                $data['created_at'] = dateTime();
            } else {
                $data['updated_at'] = dateTime();

            }

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }

            $finance_no = 'DJ' . IndexController::getRandomNum(6);
            // 创建 / 更新 待财务确认定金到账
            $confirm_data = [
                'finance_no' => $finance_no,
                'order_sn_parent' => $param['order_sn'],
                'status' => 1,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payment_voucher' => $payment_voucher,
                'payment_amount' => $param['this_request_price'],
                'this_request_price' => $param['this_request_price'],
                'type' => 1,// 类型 1 定金 2 余款
                'remark' => $param['remark'],
                'payer_name' => $param['payer_name'],
                'currency' => $orders->currency,
            ];

            // 根据收款账单信息判断是更新还是创建
            if (!$wai) {
                $confirm_data['created_at'] = dateTime();
                $accounting_information = WaAccountingInformation::created($confirm_data);
                if (!$accounting_information) {
                    return IndexController::errored('', '创建 待财务确认定金到账 失败');
                }
            } else {
                $confirm_data['updated_at'] = dateTime();
                $accounting_information = WaAccountingInformation::updated($confirm_data, $wai_condition);
                if (!$accounting_information) {
                    return IndexController::errored('', '更新 待财务确认定金到账 失败');
                }
            }

            $time = date('H:i:s', time());
            $admin_ids = [];
            // 钉钉消息通知
            if ($admin_ids) {
                foreach ($admin_ids as $kadmin) {
                    $admin_condition = [];
                    $admin_condition [] = ['id', '=', $kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '定金到账', // 标题
                        'markdown' => '哪一笔订单号是多少' . $time, // 内容
                    ];
                    $currentRoute = $request->host();

                    // 消息通知
                    if ($currentRoute == 'frontforeign.olivenev.com') {
                        $message = MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logErrorNew('confirmationDepositReceipt', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 作废-销售订单-财务确认定金余款到账
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function financeConfirmation(Request $request)
    {
        return IndexController::errored('', '20250610作废-独立出来账单业务');

        //销售订单状态
        PublicCommentController::销售订单状态;
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $wai = WaAccountingInformation::find(['finance_no' => $param['finance_no']]);
        $wai = json_decode($wai);
        if (!$wai) {

            return IndexController::errored('', '定金到账信息获取失败');
        }

        if ($wai->type == 1) {
            $status = 5; //  订单采购中
        } elseif ($wai->type == 2) {
            $status = 19; //  出口跟单中
            //判断是否已完成车务  更改车辆状态为已完成
            AccountingInformationController::syncSalesStatusByVehicles($wai->order_sn_parent, $status);

        }

        if (array_key_exists('voucher', $param)) { // 财务确认凭证
            $voucher = $param['voucher'];
        } else {
            $voucher = [];
        }

        if (array_key_exists('payer_name', $param)) { //
            $payer_name = $param['payer_name'];
        } else {
            $payer_name = $wai->payer_name;
        }


        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            if ($status == 9) {
                $describe = $adminId->nickname . '财务余款确认到账' . $wai->order_sn_parent . '状态修改为已完成(车务也已完成)';

            } else {
                $describe = $adminId->nickname . '财务余款确认到账' . $wai->order_sn_parent . '状态修改为报关中';
            }
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $wai->order_sn_parent,
                'status' => $status,
                'describe' => $describe,
                'reason' => '',
                'payer_name' => $payer_name,
                'type' => $wai->type,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => json_encode($voucher),
                'payment_amount' => $wai->this_request_price,
                'this_request_price' => $wai->this_request_price,
                'created_at' => dateTime(),
                'confirm_time' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($wai->order_sn_parent, intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '销售订单状态更新失败');
            }


            // 创建 财务确认定金到账
            $confirm_data = [
                'status' => 2,
                'finance_confirm_entry_admin_id' => $adminId->id,
                'finance_confirm_entry_admin_name' => $adminId->nickname,
                'voucher' => json_encode($voucher), // 财务确认凭证
                'type' => $wai->type,
                'payment_amount' => $wai->this_request_price,
                'this_request_price' => $wai->this_request_price,
                'payer_name' => $payer_name,
                'updated_at' => dateTime(),
            ];

            $confirm_where = [];
            $confirm_where [] = ['finance_no', '=', $param['finance_no']];
            $accounting_information = WaAccountingInformation::updated($confirm_data, $confirm_where);
            if (!$accounting_information) {
                return IndexController::errored($status_up, '财务确认到账失败');
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logErrorNew('financeConfirmation', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 作废
     * @param $sales_order_sn
     * @param $status
     * @return string|Response
     */
    public static function syncSalesStatusByVehicles($sales_order_sn, &$status)
    {
        return IndexController::errored('', '20250610作废-独立出来账单业务');
        // 获取所有订单的子订单信息
        $sales_children_condition = [];
        $sales_children_condition [] = ['order_sn_parent', '=', $sales_order_sn];
        $sales_children_data = WaOrdersRelevance::all($sales_children_condition);
        $sales_children_data = json_decode($sales_children_data);
        if ($sales_children_condition) {
            $is_vin_over = 2; // 1 未完成  2 已完成
            // 遍历子订单 查询车辆库存表判断是否配车和 配车数量
            foreach ($sales_children_data as $ksc) {
                // 获取子订单数量车型数量 和已配车数量
                if ($ksc->count == $ksc->vin_count) {

                    // 配车完成 -> 判断是否都完成退税
                    $vehicles_condition = ['sales_children_sn' => $ksc->order_sn_child];
                    $vehicles_field = ['*'];
                    $vehicles_data = WaPurchasedVehicles::all($vehicles_field, $vehicles_condition);
                    $vehicles_data = json_decode($vehicles_data);
                    if ($vehicles_data) {
                        foreach ($vehicles_data as $kv) {
                            PublicCommentController::车辆状态;
                            // 判断是否完成退税 完成车务
                            if ($kv->status != 14) {
                                // 退税未完成
                                $is_vin_over = 1; // 1 未完成  2 已完成
                                break;

                            }
                        }
                    } else {
                        // 获取子订单 车辆信息失败
                        $is_vin_over = 1; // 1 未完成  2 已完成
                        break;
                    }

                } else {
                    // 该笔订单配车未完成
                    $is_vin_over = 1; // 1 未完成  2 已完成
                    break;
                }
            }
        } else {
            // 获取子订单信息失败
            $is_vin_over = 1; // 1 未完成  2 已完成
        }

        // 车辆都配车完成后  修改销售订单为已完成 跟单中
        PublicCommentController::销售订单状态;
        if ($is_vin_over == 2) {
            $status = 9;// 跟单已完成
        }
        return 'true';
    }

    /**
     * 作废-更新-余款确认到账
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function confirmationBalanceReceived(Request $request)
    {
        return IndexController::errored('', '20250610作废-独立出来账单业务');
        //销售订单状态
        PublicCommentController::销售订单状态;
        // 订单状态 6待支付余款
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
//        $status = self::status($param['order_sn']);
//        if ($status != 6) {
//            return IndexController::errored('', '待支付余款状态才能余款确认到账');
//        }

        // 查看总金额
        $orders_sum = WaOrdersRelevance::sums(['order_sn_parent' => $param['order_sn']]);
        $orders_sum = json_decode($orders_sum);
        if (!$orders_sum) {
            return IndexController::errored('', '订单总金额获取失败');
        }
        // 查看定金      计算余款
        $order_log = WaOrdersOperateLog::find(['*'], ['order_sn_parent' => $param['order_sn'], 'type' => 1]);
        $order_log = json_decode($order_log);
        if ($order_log) {
            $result = round($orders_sum, 2) - round($order_log->this_request_price, 2);  // 待支付余款
            $result_price = round($result, 2) - round($param['this_request_price'], 2);
            if ($result_price != 0) {
                return IndexController::errored('总金额' . $orders_sum . '已支付定金' . $order_log->this_request_price . '待支付金额' . $result, '待支付余款 和 确认支付余款金额不一致');
            }
        }

        $orders = WaOrders::find(['order_sn' => $param['order_sn']]);
        $orders = json_decode($orders);
        if (!$orders) {
            return IndexController::errored('', '获取订单信息失败');
        }


        if (array_key_exists('payer_name', $param)) { //
            $payer_name = $param['payer_name'];
        } else {
            $payer_name = '';
        }


        \support\Db::beginTransaction();
        try {

            // 判断是更新还是创建
            $wai_condition = [];
            $wai_condition [] = ['order_sn_parent', '=', $param['order_sn']];
            $wai_condition [] = ['type', '=', 2]; // 尾款
            $wai = WaAccountingInformation::find($wai_condition);
            $wai = json_decode($wai);

            //操作日志记录入参
            $payment_voucher = json_encode($param['payment_voucher']);
            $describe = $adminId->nickname . '业务员确认' . $param['order_sn'] . '余款到账修改状态为待财务确认余款到账';
            $remark = $param['remark'];
            $confirm_time = dateTime(); // 确认时间
            $status = 16; //  待财务确认余款到账

            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payment_voucher' => $payment_voucher,
                'payment_amount' => $param['this_request_price'],
                'this_request_price' => $param['this_request_price'],
                'payer_name' => $payer_name,
                'type' => 2,// 类型 1 定金 2 余款
                'created_at' => dateTime(),
            ];

            // 根据收款账单信息判断是更新还是创建
            if (!$wai) {
                $data['created_at'] = dateTime();
            } else {
                $data['updated_at'] = dateTime();

            }
            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }
            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }

            $finance_no = 'YK' . IndexController::getRandomNum(6);
            // 创建 待财务确认余款到账
            $confirm_data = [
                'finance_no' => $finance_no,
                'order_sn_parent' => $param['order_sn'],
                'status' => 1,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payment_voucher' => $payment_voucher,
                'payment_amount' => $param['this_request_price'],
                'this_request_price' => $param['this_request_price'],
                'type' => 2,// 类型 1 定金 2 余款
                'payer_name' => $payer_name,
                'currency' => $orders->currency,
            ];

            // 根据收款账单信息判断是更新还是创建
            if (!$wai) {
                $confirm_data['created_at'] = dateTime();
                $accounting_information = WaAccountingInformation::created($confirm_data);
                if (!$accounting_information) {
                    return IndexController::errored('', '创建 待财务确认余款到账 失败');
                }
            } else {
                $confirm_data['updated_at'] = dateTime();
                $accounting_information = WaAccountingInformation::updated($confirm_data, $wai_condition);
                if (!$accounting_information) {
                    return IndexController::errored('', '更新 待财务确认余款到账 失败');
                }
            }

            $time = date('H:i:s', time());
            $admin_ids = [];
            // 钉钉消息通知
            if ($admin_ids) {
                foreach ($admin_ids as $kadmin) {
                    $admin_condition = [];
                    $admin_condition [] = ['id', '=', $kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '尾款确认到账', // 标题
                        'markdown' => '哪一笔订单的尾款确认到账' . $time, // 内容
                    ];
                    $currentRoute = $request->host();

                    // 消息通知
                    if ($currentRoute == 'frontforeign.olivenev.com') {
                        $message = MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {

            IndexController::logErrorNew('confirmationBalanceReceived', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

}